<template>
    <div class="dropdown" :class="{ 'is-active': isActive }" @click="toggleActive">
      <div class="dropdown-trigger">
        <slot name="trigger"></slot>
      </div>
      <div class="dropdown-menu" :class="[placementClass, { 'is-hidden': !isActive }]" ref="dropdownMenu">
        <slot></slot>
      </div>
    </div>
  </template>
  
  <script>
  import { defineComponent, ref, watch, onMounted, onUnmounted } from 'vue'
  
  export default defineComponent({
    name: 'pui-Dropdown',
    props: {
      placement: {
        type: String,
        default: 'top-end',
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      popper: {
        type: Object,
        default: null,
      },
    },
    emits: ['update:disabled'],
    setup(props) {
      const isActive = ref(false)
  
      const placementClass = ref(`dropdown-menu--${props.placement}`)
  
      watch(
        () => props.placement,
        () => {
          placementClass.value = `dropdown-menu--${props.placement}`
        }
      )
  
      const toggleActive = () => {
        if (props.disabled) return
        isActive.value = !isActive.value
      }
  
      // @ts-ignore
      const handleClickOutside = (event) => {
        if (!isActive.value || !props.popper) return
        const dropdownMenu = document.querySelector('.dropdown-menu')
        const popperElement = props.popper.element || dropdownMenu
        if (!popperElement.contains(event.target)) {
          isActive.value = false
        }
      }
  
      onMounted(() => {
        document.addEventListener('click', handleClickOutside)
      })
  
      onUnmounted(() => {
        document.removeEventListener('click', handleClickOutside)
      })
  
      return {
        isActive,
        placementClass,
        toggleActive,
      }
    },
  })
  </script>
  
  <style scoped>
  .dropdown {
    position: relative;
    display: inline-block;
  }
  
  .dropdown-trigger {
    cursor: pointer;
  }
  
  .dropdown-menu {
    position: absolute;
    background-color: #fff;
    border: 1px solid #c8c8c8;
    border-radius: 0px;
    box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.15);
    min-width: 80px;
    z-index: 10;
    opacity: 0;
    transition: opacity 0.2s ease;
  }
  
  .dropdown-menu.is-hidden {
    display: none;
  }
  
  .dropdown-menu--top-start {
    top: -10px;
    left: 0;
  }
  
  .dropdown-menu--top-end {
    top: -10px;
    right: 0;
  }
  
  .dropdown-menu--bottom-start {
    top: 100%;
    left: 0;
  }
  
  .dropdown-menu--bottom-end {
    top: 100%;
    right: 0;
  }
  
  .dropdown.is-active .dropdown-menu {
    opacity: 1;
  }
  </style>
  